package com.party.web.biz.quartz.factory;

import com.party.common.constant.Constant;
import com.party.common.reflect.ReflectUtils;
import com.party.core.model.notify.Event;
import com.party.web.biz.quartz.impl.SchsduleService;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.List;

/**
 * 同步任务工厂类
 * Created by wei.li
 *
 * @date 2017/4/12 0012
 * @time 10:19
 */

@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class SyncJobFactory extends QuartzJobBean {

    private static final Logger logger = LoggerFactory.getLogger(SyncJobFactory.class);

    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        boolean isBiz = jobDataMap.getBoolean(SchsduleService.IS_BIZ);
        if (!isBiz) {
            // 不是业务, 就走以前的路线
            Event event = (Event) context.getMergedJobDataMap().get(Constant.JOB_PARAM_KEY);
            logger.info("运行的定时任务是{}, 详情{}", event.getName(), event.toString());

            ReflectUtils.invokMethod(event.getClassName(), event.getMethod());
        } else {
            // 是业务, 就走新的程序动态生成定时任务路线
            Event event = (Event) jobDataMap.get(Constant.JOB_PARAM_KEY);

            String triggerName = context.getTrigger().getKey().getName();
            String jobName = context.getJobDetail().getKey().getName();
            if (!triggerName.contains(jobName)) {
                logger.error("运行定时任务类{}的方法{}时出错, triggerName {}中没有jobName {}",
                        event.getClassName(), event.getMethod(), triggerName, jobName);
                return;
            }

            String id = triggerName.substring(jobName.concat("_").length());

            Object paramsObject = jobDataMap.get(SchsduleService.PARAMS);
            Object[] params;
            if (null == paramsObject) {
                params = new Object[]{id};
            } else {
                List<Object> list = (List<Object>) paramsObject;
                params = new Object[list.size() + 1];
                for (int i = 0, j = list.size(); i < j; i++) {
                    params[i] = list.get(i);
                }
                params[params.length - 1] = id;
            }

            logger.info("运行的定时任务是{}, 详情{}", event.getName(), event.toString());
            ReflectUtils.invokeMethod(event.getClassName(), event.getMethod(), params);
        }
    }
}
